package com.studysystem.controller;

import com.studysystem.dto.CourseSimpleDTO;
import com.studysystem.entity.Course;
import com.studysystem.repository.CourseRepository;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/courses")
public class CourseController {
    private final CourseRepository courseRepository;

    public CourseController(CourseRepository courseRepository) {
        this.courseRepository = courseRepository;
    }

    // 获取所有课程基本信息
    @GetMapping
    public List<CourseSimpleDTO> getAllCourses() {
        List<Course> courses = courseRepository.findAll();
        return courses.stream().map(this::toSimpleDTO).collect(Collectors.toList());
    }

    // 获取单个课程详情
    @GetMapping("/{id}")
    public CourseSimpleDTO getCourseById(@PathVariable Long id) {
        return courseRepository.findById(id).map(this::toSimpleDTO).orElse(null);
    }

    private CourseSimpleDTO toSimpleDTO(Course course) {
        CourseSimpleDTO dto = new CourseSimpleDTO();
        dto.setId(course.getId());
        dto.setTitle(course.getTitle());
        dto.setInstructorName(course.getInstructor().getFullName() != null ? course.getInstructor().getFullName() : course.getInstructor().getUsername());
        dto.setDescription(course.getDescription());
        dto.setThumbnail(course.getThumbnail());
        return dto;
    }
} 